/*
 * Copyright © 2012，the original authors or Tianyuan DIC Computer Co., Ltd.
 *
 * Please see the tydic success stories and it solutions 
 *
 *      http://www.tydic.com/Default.aspx
 *
 * Statement: This document's code after sufficiently has not permitted does not have 
 * any way dissemination and the change, once discovered violates the stipulation, will
 * receive the criminal sanction.
 * Address: 3/F,T3 Building, South 7th Road, South Area, Hi-tech Industrial park, Shenzhen, P.R.C.
 * Email: webmaster@tydic.com　
 * Tel: +86 755 26745688 
 */
package com.lantu.draw.framework;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.result.StrutsResultSupport;
import org.codehaus.jackson.map.ObjectMapper;
import com.opensymphony.xwork2.ActionInvocation;

public class JSONResult extends StrutsResultSupport {

	private static final long serialVersionUID = 5301145935889262957L;
	
	private boolean ignoreHierarchy = false;
	
    private boolean noCache = false;
    
	private String root;
	
	private String contentType; 
	
	public boolean isIgnoreHierarchy() {
		return ignoreHierarchy;
	}

	public void setIgnoreHierarchy(boolean ignoreHierarchy) {
		this.ignoreHierarchy = ignoreHierarchy;
	}

	public boolean isNoCache() {
		return noCache;
	}

	public void setNoCache(boolean noCache) {
		this.noCache = noCache;
	}

	public String getRoot() {
		return root;
	}

	public void setRoot(String root) {
		this.root = root;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	@Override
	protected void doExecute(String value, ActionInvocation actionInvocation) throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		if (contentType == null) { 
			contentType = "text/plain; charset=UTF-8";
		} 
		response.setContentType(contentType); 
		
		try {
			if(root != null && !"".equals(root)) {
				Object valueRoot = actionInvocation.getStack().findValue(root);
				if(valueRoot != null) {
					PrintWriter out = response.getWriter();
					try {
						ObjectMapper mapper = new ObjectMapper();
						mapper.writeValue(out, valueRoot);
						out.flush();  
					} 
					finally {
						if(out != null) {
							out.close(); 
						}
					}
				}
			}
		}
		catch(Exception e) {
			throw new ErrorException("E0000",e);
		}
	}

}

